const { RSA_NO_PADDING } = require('constants');
let express = require('express');
let router = express.Router();
let fs = require('fs');
let pathLib = require('path');
let mgdb = require('../../utils/mgdb')

//管理端结果，返数据动作，前端渲染

// 操作的集合名称： goods
// title:产品名称九
// sort :所属分类：第一系列
// times:发布时间：2018-04-23

// { "_id" : ObjectId("5fd47ea8041c24741ca45e9d"), "title" : "陶子杰", "sort" : "陶子杰", "times" : "发布事件", "time" : 1607761576247, "imgUrl" : "/upload/caselist/3180f87330b974ddc4b20d29348ec665.jpg" }

//增加库
router.post('/',(req,res,next)=>{
  //抓取参数
  let {title,sort,times} = req.body;
  let time = Date.now();
  // 设置imgUrl的路径 和随机后缀名称
  let imgUrl;
  req.files && req.files.forEach((file,index)=>{
    imgUrl = '/upload/goods/' + file.filename + pathLib.parse(file.originalname).ext
    fs.renameSync(
      file.path,
      file.path + pathLib.parse(file.originalname).ext
    )
  })
  // 设置为当前参数为必传参数
  if(!title){
    res.send({err:1,msg:'title标题为必传参数'});
        return;
  }else if(!sort){
    res.send({err:1,msg:'sort分类为必传参数'});
        return;
  }else if(!times){
    res.send({err:1,msg:'times发布时间为必传参数'});
        return;
  }else if(!imgUrl){
    res.send({err:1,msg:'imgUrl商品图片为必传参数'});
        return;
  }

  //开库，写入   goods
  mgdb.open({collectionName:'goods'}).then(
    ({collection,client})=>{
      //插入
      let data = {title,sort,times,time,imgUrl};
      collection.insertOne(data,(err,result)=>{
        if(!err && result.result.n > 0){
          res.send({
            err:0,
            msg:'成功',
            data:{
              _id: result.insertedId,
              ...data//解构
            }
          })
        }else{
          res.send({err:1,msg:'添加失败'})  
        }
        client.close()
      })
    }
  )
})

//删除库
router.delete('/:_id',(req,res,next)=>{
  let _id = req.params._id;
  if(!_id){
    res.send({err:1,msg:'_id为必传参'})
    return;
  }
  mgdb.open({collectionName:'goods'}).then(
    ({collection,client,ObjectId})=>{
      collection.deleteOne({_id:ObjectId(_id)},(err,result)=>{
        if(!err && result.result.n>0){
          res.send({err:0,msg:'删除成功'})
        }else {
          res.send({err:0,msg:'删除失败'})
        }
        client.close()
      })
    }
  )

})

//修改库
router.patch('/:_id',(req,res,next)=>{
  let _id = req.params._id;
  if(!_id){
    res.send({err:1,msg:'_id为必传参'})
    return;
  }
  mgdb.open({collectionName:'goods'}).then(
    ({collection,client,ObjectId})=>{
      //查询到所有key 和 客户端传入的key 合并，删除更新前的文件
      collection.find({_id:ObjectId(_id)}).toArray((err,result)=>{
        if(!err && result.length>0){
          //整理要合并的数据
          let {title,sort,time} = req.body;
          title=title||result[0].title;
          sort=sort||result[0].sort;
          time=time||result[0].time
       
          let imgUrl;
          req.files && req.files.forEach((file,index)=>{
       
            imgUrl = '/upload/caselist/' + file.filename + pathLib.parse(file.originalname).ext
              //删除以前  result[0].detail.auth_icon   -> res.unlink
            fs.renameSync(
              file.path,
              file.path + pathLib.parse(file.originalname).ext
            )
          })

          imgUrl = imgUrl || result[0].imgUrl;
          //修改
          collection.updateOne({
            _id:ObjectId(_id)
          },{
            $set:{title,imgUrl,sort,time},
          },(err,result)=>{
            if(!err && result.result.n>0){
              res.send({err:0,msg:'修改成功'})
            }else{
              res.send({err:1,msg:'修改失败'})
            }
            client.close()
          })
        }else{
          res.send({err:0,msg:'修改失败,数据不存在，傻笑重时'})
        }
      })

    })
})


//查排 调用api接口
// localhost:3000/api/list/caselist/
router.get('/',(req,res,next)=>{})
module.exports=router;